import java.io.*;
import java.util.*;

import javax.xml.xpath.*;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

public class Presult {

	List resultlist;
	double hit=-1;
	
	public Presult(List l, double hit)
	{
		resultlist = l;
		this.hit=hit;
	}
	
	public Presult(InputStream input)throws Exception
	{
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
		
		XPathFactory factory = XPathFactory.newInstance();
		XPath xPath=factory.newXPath();

		hit=((Double)xPath.evaluate("/ysearchresponse/resultset_web/@totalhits",response, XPathConstants.NUMBER)).doubleValue();
		System.out.println("hit: "+hit);
		NodeList nodes = (NodeList)xPath.evaluate("/ysearchresponse/resultset_web/result", response, XPathConstants.NODESET);
		int nodeCount = nodes.getLength();
        
		resultlist = new ArrayList();
		for (int i = 0; i < nodeCount; i++) {
			
			String title = (String)xPath.evaluate("title", nodes.item(i), XPathConstants.STRING);
			String summary = (String)xPath.evaluate("abstract", nodes.item(i), XPathConstants.STRING);
			String url = (String)xPath.evaluate("url", nodes.item(i), XPathConstants.STRING);
			
			System.out.println("URL: " + url);
			resultlist.add(new Result(title, summary, url));
			
			}
	}
	
	public Iterator iterator()
	{
		return resultlist.iterator();
	}
	
	public int getSize()
	{
		return resultlist.size();
	}
	
	public Result get(int i)
	{
		return (Result)resultlist.get(i);
	}
	
	public double getHit()
	{
		return hit;
	}
}
